package com.android.binderserverclient0
import android.content.Context
import androidx.datastore.preferences.core.Preferences
import androidx.datastore.preferences.core.booleanPreferencesKey
import androidx.datastore.preferences.core.doublePreferencesKey
import androidx.datastore.preferences.core.edit
import androidx.datastore.preferences.core.floatPreferencesKey
import androidx.datastore.preferences.core.intPreferencesKey
import androidx.datastore.preferences.core.longPreferencesKey
import androidx.datastore.preferences.core.stringPreferencesKey
import androidx.datastore.preferences.preferencesDataStore
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.map

val Context.myDataStore by preferencesDataStore("file_name")

suspend fun <T> putV2(context: Context, key: String, value: Any, type: T) {
    val keyValue = getKey(key, type)
    context.myDataStore.edit {
        it[keyValue] = value as T
    }
}

suspend fun <T> Context.putV1(key: String, value: Any, type: T) {
    val keyValue = getKey(key, type)
    this.myDataStore.edit {
        it[keyValue] = value as T
    }
}

fun <T> getValueV2(context: Context,key: String,type: T) : Flow<Any?> {
    val keyValue = getKey(key, type)
    val flow = context.myDataStore.data.map {
        it[keyValue]
    }
    return flow
}

fun <T> Context.getValueV1(key: String,type: T) : Flow<Any?> {
    val keyValue = getKey(key, type)
    val flow = this.myDataStore.data.map {
        it[keyValue]
    }
    return flow
}

private fun <T> getKey(key: String, type: T): Preferences.Key<T> {

    val keyValue: Preferences.Key<T>?

    val typeValue = type.toString()

    if (typeValue.endsWith(Int::class.java.name)) {

        keyValue = intPreferencesKey(key) as Preferences.Key<T>
    } else if (typeValue.endsWith(Float::class.java.name)) {

        keyValue = floatPreferencesKey(key) as Preferences.Key<T>
    } else if (typeValue.endsWith(Long::class.java.name)) {

        keyValue = longPreferencesKey(key) as Preferences.Key<T>
    } else if (typeValue.endsWith(Double::class.java.name)) {

        keyValue = doublePreferencesKey(key) as Preferences.Key<T>
    } else if (typeValue.endsWith(String::class.java.name)) {

        keyValue = stringPreferencesKey(key) as Preferences.Key<T>
    } else if (typeValue.endsWith(Boolean::class.java.name)) {

        keyValue = booleanPreferencesKey(key) as Preferences.Key<T>
    } else {
        throw IllegalArgumentException("Key is not support,you need check your type")
    }

    return keyValue
}